import { getOrderList, getMyOrders, createOrder, updateOrderStatus, cancelOrder, deleteOrder } from '@/api/order'

const state = {
  orders: [],
  total: 0,
  currentOrder: null
}

const mutations = {
  SET_ORDERS: (state, { list, total }) => {
    state.orders = list
    state.total = total
  },
  SET_CURRENT_ORDER: (state, order) => {
    state.currentOrder = order
  },
  UPDATE_ORDER_STATUS: (state, { id, status }) => {
    const order = state.orders.find(item => item.id === id)
    if (order) {
      order.status = status
    }
  }
}

const actions = {
  // 获取订单列表
  async getOrders({ commit }, params) {
    try {
      const response = await getOrderList(params)
      if (response.code === 200) {
        commit('SET_ORDERS', {
          list: response.data || response.list || [],
          total: response.total || (response.data ? response.data.length : 0)
        })
        return response
      } else {
        throw new Error(response.message || '获取订单列表失败')
      }
    } catch (error) {
      console.error('获取订单列表失败:', error)
      throw error
    }
  },

  // 获取我的订单
  async getMyOrderList({ commit }, params) {
    try {
      const response = await getMyOrders(params)
      if (response.code === 200) {
        console.log('获取到的订单数据:', response)
        
        // 确保订单项数据格式正确
        const orders = (response.data?.list || response.data || []).map(order => {
          // 处理订单项数据
          if (!order.orderItems && order.items) {
            order.orderItems = order.items
          }
          
          // 查找订单商品详情
          if (order.orderItems && order.orderItems.length > 0) {
            // 处理订单项，确保有正确的名称和图片
            order.orderItems = order.orderItems.map(item => {
              // 如果没有商品名称，尝试设置一个默认名称
              if (!item.name && !item.productName) {
                item.productName = `商品 #${item.productId}`
              }
              return item
            })
          }
          
          // 调试日志
          console.log(`订单[${order.id}]: 状态=${order.status}, 创建时间=${order.createdTime}, 包含${(order.orderItems || []).length}个商品`)
          
          return order
        })
        
        commit('SET_ORDERS', {
          list: orders,
          total: response.data?.total || response.total || orders.length
        })
        return response
      } else {
        throw new Error(response.message || '获取我的订单失败')
      }
    } catch (error) {
      console.error('获取我的订单失败:', error)
      throw error
    }
  },

  // 创建订单
  async createOrder({ commit }, orderData) {
    try {
      const response = await createOrder(orderData)
      if (response.code === 200) {
        return response
      } else {
        throw new Error(response.message || '创建订单失败')
      }
    } catch (error) {
      console.error('创建订单失败:', error)
      throw error
    }
  },

  // 更新订单状态
  async updateOrderStatus({ commit }, { id, status }) {
    try {
      const response = await updateOrderStatus(id, status)
      if (response.code === 200) {
        commit('UPDATE_ORDER_STATUS', { id, status })
        return response
      } else {
        throw new Error(response.message || '更新订单状态失败')
      }
    } catch (error) {
      console.error('更新订单状态失败:', error)
      throw error
    }
  },

  // 取消订单
  async cancelOrder({ commit }, id) {
    try {
      const response = await cancelOrder(id)
      if (response.code === 200) {
        commit('UPDATE_ORDER_STATUS', { id, status: 'cancelled' })
        return response
      } else {
        throw new Error(response.message || '取消订单失败')
      }
    } catch (error) {
      console.error('取消订单失败:', error)
      throw error
    }
  },

  // 删除订单
  async deleteOrder({ commit, state }, id) {
    try {
      const response = await deleteOrder(id)
      if (response.code === 200) {
        const newOrders = state.orders.filter(order => order.id !== id)
        commit('SET_ORDERS', {
          list: newOrders,
          total: state.total - 1
        })
        return response
      } else {
        throw new Error(response.message || '删除订单失败')
      }
    } catch (error) {
      console.error('删除订单失败:', error)
      throw error
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 